package top.yuyufeng.mbuy.dao;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import top.yuyufeng.mbuy.dto.CartDTO;
import top.yuyufeng.mbuy.entity.Cart;
import top.yuyufeng.mbuy.mapper.CartMapper;

import java.util.List;

@Repository
public class CartDao {

    @Autowired
    private CartMapper cartMapper;

    public void insert(Cart cart) {
        cartMapper.insertSelective(cart);
    }


    public CartDTO get(CartDTO cartDTO) {
        Cart cartQuery = new Cart();
        BeanUtils.copyProperties(cartDTO, cartQuery);
        Cart cartRecord = cartMapper.selectOne(cartQuery);
        CartDTO cartResult = new CartDTO();
        BeanUtils.copyProperties(cartRecord, cartResult);
        return cartResult;
    }

    public CartDTO getByUserIdAndProductId(Integer userId, Integer productId) {
        Cart cartQuery = new Cart();
        cartQuery.setUserId(userId);
        cartQuery.setProductId(productId);
        Cart cartRecord = cartMapper.selectOne(cartQuery);
        if (null == cartRecord) {
            return null;
        }
        CartDTO cartResult = new CartDTO();
        BeanUtils.copyProperties(cartRecord, cartResult);
        return cartResult;
    }

    public List<Cart> getByUserId(Integer userId) {
        Cart t = new Cart();
        t.setUserId(userId);
        return cartMapper.select(t);
    }

    public Cart getByUserIdAndProductId(Integer userId) {
        Cart t = new Cart();
        t.setUserId(userId);
        return cartMapper.selectOne(t);
    }

    public void deleteById(Integer id) {
        cartMapper.deleteByPrimaryKey(id);
    }

    public void deleteByUserId(Integer userId) {
        Cart t = new Cart();
        t.setUserId(userId);
        cartMapper.delete(t);
    }

    public void update(CartDTO cartDTO) {
        Cart cartUpdate = new Cart();
        BeanUtils.copyProperties(cartDTO, cartUpdate);
        cartMapper.updateByPrimaryKeySelective(cartUpdate);
    }



    public List<CartDTO> listByUserIdWithDetail(Integer userId) {
      return  cartMapper.listByUserIdWithDetail(userId,null);
    }

    public List<CartDTO> listByUserIdWithDetailChecked(Integer userId) {
        return  cartMapper.listByUserIdWithDetail(userId,1);
    }
}
